#include "stdio.h"
#include "SDL2/SDL.h"
#include "world.h"
#include "sdl_helper.h"
#include <time.h>

SDL_Window *win;

extern struct dd_world *world_main_create();

int init_sdl() {

	// init sdl
	if (SDL_Init(SDL_INIT_VIDEO) != 0) {
		printf("SDL_Init Error: %s\n", SDL_GetError());
		return 1;
	}

	// open window
	win = SDL_CreateWindow("Hello World!", 100, 100, DD_GAME_WIDTH, DD_GAME_HEIGHT, SDL_WINDOW_SHOWN);
	if (!win){
		printf("SDL_CreateWindow Error: %s\n", SDL_GetError());
		SDL_Quit();
		return 1;
	}

	// create renderer
	dd_ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
	if (!dd_ren){
		SDL_DestroyWindow(win);
		printf("SDL_CreateRenderer Error: %s\n", SDL_GetError());
		SDL_Quit();
		return 1;
	}

	if ((IMG_Init(IMG_INIT_PNG) & IMG_INIT_PNG) != IMG_INIT_PNG){
		printf("IMG_Init Error: %s\n", SDL_GetError());
		SDL_Quit();
		return 1;
	}

	return 0;

}

int main() {

	srand((unsigned int) time(NULL));

	DD_GAME_WIDTH = 640;
	DD_GAME_HEIGHT = 480;

	// init sdl, including window and renderer
	if (init_sdl() != 0) return -1;

	// create world
	dd_cworld = world_main_create();

	dd_game_running = 1;
	SDL_Event e;

	// loop
	while (dd_game_running){

		while (SDL_PollEvent(&e)) {
			switch (e.type) {
				case SDL_QUIT:
					dd_game_running = 0;
					break;

				case SDL_KEYDOWN:
					dd_cworld->key(dd_cworld, e.key.keysym.scancode, DD_KEY_STATE_PRESSED);
					break;

				case SDL_KEYUP:
					dd_cworld->key(dd_cworld, e.key.keysym.scancode, DD_KEY_STATE_RELEASED);
					break;

				case SDL_MOUSEBUTTONDOWN:
					//printf("mouse button down on %d,%d\n", e.button.x, e.button.y);
					dd_cworld->click(dd_cworld, e.button.x, e.button.y);
					break;

				case SDL_MOUSEBUTTONUP:
					//printf("mouse up down on %d,%d\n", e.button.x, e.button.y);
					break;
			}
		}

		// update
		dd_cworld->update(dd_cworld);

		// draw
		SDL_RenderClear(dd_ren);
		dd_cworld->draw(dd_cworld);
		SDL_RenderPresent(dd_ren);

		// pause, till next frame
		SDL_Delay(1000/30);

		// check if menu wants to quit
		if (dd_cworld->next == -1) dd_game_running = 0;
	}

	free(dd_cworld);
	SDL_DestroyRenderer(dd_ren);
	SDL_DestroyWindow(win);
	IMG_Quit();
	SDL_Quit();
	return 0;
}
